//导入模型
import { Book } from '../model/Book.js'
import { Op } from 'sequelize'

//图书列表
const fn_list = async (ctx, next) => {
  const keyword = ctx.request.query.keyword  
  let where = {}
  if (keyword) {
    where = {
      [Op.or]: [
        { bookName: { [Op.like]: `%${keyword}%` } },
        { author: { [Op.like]: `%${keyword}%` } },
        { descriptions: { [Op.like]: `%${keyword}%` } }
      ]
    }
  }
  // 查询数据库所有的图书
  const books = await Book.findAll({where})
  ctx.body = {
    code: 1000,
    msg: '获取图书列表成功',
    data: books
  }

}

//图书信息
const fn_getById = async (ctx, next) => {
  //获取url的id
  const id = ctx.params.id
  //去数据库查询
  const book = await Book.findByPk(id)
  ctx.body = {
    code: 1000,
    msg: '成功',
    data: book
  }
}

//添加图书
const fn_add = async (ctx, next) => {
  const book = ctx.request.body
  await Book.create(book)
  ctx.body = {
    code: 1000,
    msg: '添加成功',
    data: null
  }
}

//修改图书
const fn_updata = async (ctx, next) => {
  const id = ctx.params.id
  const book = ctx.request.body
  await Book.update(book, {
    where: {
      id: id
    }
  })

  ctx.body = {
    code: 1000,
    msg: '修改成功',
    data: null
  }
}

//删除图书
const fn_delete = async (ctx, next) => {
  let id = ctx.params.id || 0

  await Book.destroy({
    where: {
      id: id
    }
  })

  ctx.body = {
    code: 1000,
    msg: '删除成功',
    data: null
  }
}

export default [
  {
    method: 'get',
    url: '/books',
    fn: fn_list
  },
  {
    method: 'get',
    url: '/books/:id',
    fn: fn_getById
  },
  {
    method: 'post',
    url: '/books',
    fn: fn_add
  },
  {
    method: 'put',
    url: '/books/:id',
    fn: fn_updata
  },
  {
    method: 'delete',
    url: '/books/:id',
    fn: fn_delete
  }
]